package dynamic.ibatis.binding;

/*
 *    Copyright 2009-2023 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

import dynamic.ibatis.builder.annotation.DMapperAnnotationBuilder;
import dynamic.ibatis.session.DConfiguration;
import dynamic.ibatis.session.DSqlSession;
import dynamic.metadata.EntityClass;
import org.apache.ibatis.binding.BindingException;


import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Clinton Begin
 * @author Eduardo Macarron
 * @author Lasse Voss
 */
public class DMapperRegistry {

    private final DConfiguration config;
    private final Map<Class<?>,Map<EntityClass,MapperProxyFactory<?>>> knownMappers = new HashMap<>();

    public DMapperRegistry(DConfiguration config) {
        this.config = config;
    }

    @SuppressWarnings("unchecked")
    public <T> T getMapper(Class<T> type, EntityClass entityClass, DSqlSession sqlSession) {
        final Map<EntityClass,MapperProxyFactory<?>> map = knownMappers.get(type);
        if (map == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        }
        final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) map.get(entityClass);
        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        }
        try {
            return mapperProxyFactory.newInstance(sqlSession);
        } catch (Exception e) {
            throw new BindingException("Error getting mapper instance. Cause: " + e, e);
        }
    }

    public <T> boolean hasMapper(Class<T> type,EntityClass entityClass) {
        return knownMappers.containsKey(type)&&knownMappers.get(type).containsKey(entityClass);
    }

    public <T> void addMapper(Class<T> type,EntityClass entityClass) {
        if (type.isInterface()) {
            if (hasMapper(type, entityClass)) {
                throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
            }
            boolean loadCompleted = false;
            try {
                if(knownMappers.containsKey(type)){
                    knownMappers.get(type).put(entityClass,new MapperProxyFactory<>(type));
                }else{
                    HashMap<EntityClass,MapperProxyFactory<?>> map = new HashMap<>();
                    map.put(entityClass, new MapperProxyFactory<>(type));
                    knownMappers.put(type,map);
                }

                // It's important that the type is added before the parser is run
                // otherwise the binding may automatically be attempted by the
                // mapper parser. If the type is already known, it won't try.
                DMapperAnnotationBuilder parser = new DMapperAnnotationBuilder(config, type,entityClass);
                parser.parse();
                loadCompleted = true;
            } finally {
                if (!loadCompleted) {
                    knownMappers.remove(type);
                }
            }
        }
    }

    /**
     * Gets the mappers.
     *
     * @return the mappers
     *
     * @since 3.2.2
     */
    public Collection<Class<?>> getMappers() {
        return Collections.unmodifiableCollection(knownMappers.keySet());
    }

    /**
     * Adds the mappers.
     *
     * @param packageName
     *          the package name
     * @param superType
     *          the super type
     *
     * @since 3.2.2
     */
//    public void addMappers(String packageName, Class<?> superType) {
//        ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>();
//        resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
//        Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
//        for (Class<?> mapperClass : mapperSet) {
//            addMapper(mapperClass);
//        }
//    }

    /**
     * Adds the mappers.
     *
     * @param packageName
     *          the package name
     *
     * @since 3.2.2
     */
//    public void addMappers(String packageName) {
//        addMappers(packageName, Object.class);
//    }

}

